import {
  getGroupMemberList,
  clickNum,
  cardRank,
  groupCardWall
} from '../../apis/group';
import {
  toMailList
} from "../../apis/card";
const app = getApp();

Page({
  data: {
    titleTop: 0,
    titleHeight: 0,
    cardInfo: {},
    memberList: [],
    pageNum: 1,
    isHaveMore: true,
    wallCurrent: 0,
    imageCurrent: 0,
    isRequest: false
  },

  onLoad(options) {
    let menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      titleTop: menu.top + 2,
      titleHeight: menu.height,
      ...options
    });
    if (options.type === 'history') {
      wx.getStorage({
        key: 'historyPreview',
        success: res => {
          let arr = JSON.parse(res.data);
          arr = arr.map(v => {
            if (!new RegExp('https://').test(v.avatar) && !new RegExp('http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
            if (v.imageList) v.imageList = v.imageList.map(val => {
              if (!new RegExp('https://').test(val) && !new RegExp('http://').test(val)) val = app.globalData.url + val;
              return val
            });
            return {
              ...v,
              current: 0
            }
          });
          this.setData({
            memberList: arr,
            wallCurrent: options.current,
            cardInfo: arr[options.current]
          });
        }
      });
    } else if (options.type === 'cardWall') {
      this.getCardWall(options.groupId);
      this.upClickNum(options.cardId);
    } else if (options.type === 'scroll') {
      this.getGroupCardWall(options.cardId, options.groupId);
    } else if (options.type === 'group') {
      this.getGroupMember(options.groupId, 1, 16, '', JSON.parse(options.card));
      this.upClickNum(JSON.parse(options.card).cardId);
    };
  },

  // 右上角分享功能
  onShareAppMessage() {
    return {
      title: this.data.cardInfo.userName + '的快名片',
      path: `/pages/cardPreview/index?type=share&cardId=${this.data.cardInfo.cardId}`,
      imageUrl: `${this.data.cardInfo.avatar}`
    }
  },

  upClickNum(cardId) {
    clickNum(this.data.groupId, cardId).then(res => {});
  },

  // 获取群组成员列表
  getGroupMember(groupId, pageNum, pageSize, type, card) {
    if (this.data.isRequest) return
    this.setData({
      isRequest: true
    });
    getGroupMemberList(groupId, pageNum, pageSize).then(res => {
      if (res.data.code === 200) {
        let {
          rows,
          total
        } = res.data;
        if (card) {
          if (rows.findIndex(v => v.cardId === card.cardId) != -1) {
            rows.splice(rows.findIndex(v => v.cardId === card.cardId), 1);
          };
          if (type !== 'refresh') {
            rows.unshift(card);
          };
        };
        rows = rows.map(v => {
          if (!new RegExp('https://').test(v.avatar) && !new RegExp('http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
          if (v.imageList) v.imageList = v.imageList.map(val => {
            if (!new RegExp('https://').test(val) && !new RegExp('http://').test(val)) val = app.globalData.url + val;
            return val
          });
          return {
            ...v,
            current: 0
          }
        });
        if (type === 'refresh') {
          wx.hideLoading({});
          this.setData({
            wallCurrent: 0,
            memberList: rows,
            cardInfo: rows[0],
            isRequest: false
          });
        } else {
          this.setData({
            memberList: rows,
            cardInfo: card,
            isRequest: false,
            wallCurrent: 0
          });
        };
        if (this.data.memberList.length + (this.data.pageNum - 1) * 16 === total) {
          this.setData({
            isHaveMore: false
          });
        };

        wx.getStorage({
          key: 'historyPreview',
          success: res => {
            let arr = JSON.parse(res.data);
            if (arr.some(v => v.cardId == this.data.cardInfo.cardId || v.relCardId == this.data.cardInfo.cardId)) arr.splice(arr.findIndex(v => v.cardId == this.data.cardInfo.cardId || v.relCardId == this.data.cardInfo.cardId), 1);
            arr.unshift(this.data.cardInfo);
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'historyPreview'
            });
          },
          fail: res => {
            let arr = [this.data.cardInfo];
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'historyPreview'
            });
          }
        });
      };
    });
  },

  getCardWall(id) {
    cardRank(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        data = data.map(v => {
          if (!new RegExp('https://').test(v.avatar) && !new RegExp('http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
          if (v.imageList) v.imageList = v.imageList.map(val => {
            if (!new RegExp('https://').test(val) && !new RegExp('http://').test(val)) val = app.globalData.url + val;
            return val
          });
          return {
            ...v,
            current: 0
          }
        });
        this.setData({
          memberList: data,
          cardInfo: data[this.data.current],
          wallCurrent: this.data.current
        });

        wx.getStorage({
          key: 'historyPreview',
          success: res => {
            let arr = JSON.parse(res.data);
            if (arr.some(v => v.cardId == this.data.cardInfo.cardId || v.relCardId == this.data.cardInfo.cardId)) arr.splice(arr.findIndex(v => v.cardId == this.data.cardInfo.cardId || v.relCardId == this.data.cardInfo.cardId), 1);
            arr.unshift(this.data.cardInfo);
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'historyPreview'
            });
          },
          fail: res => {
            let arr = [this.data.cardInfo];
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'historyPreview'
            });
          }
        });
      };
    });
  },

  // 名片墙
  getGroupCardWall(cardId, groupId) {
    groupCardWall(groupId).then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;
        rows.forEach((v, i) => {
          if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) app.globalData.url + v.avatar;
        });
        this.setData({
          cardWallList: rows
        });
      };
    });
  },

  wallChange(e) {
    let {
      current
    } = e.detail;
    if (current === this.data.memberList.length && this.data.isHaveMore && this.data.type === 'group') {
      wx.showLoading({
        title: '加载中...'
      });
      this.setData({
        pageNum: this.data.pageNum - 0 + 1,
        memberList: []
      });
      this.getGroupMember(this.data.groupId, this.data.pageNum, 16, 'refresh', JSON.parse(this.data.card));
    } else {
      if (this.data.type != 'history') this.upClickNum(this.data.memberList[current].cardId);
      this.setData({
        cardInfo: this.data.memberList[current],
        wallCurrent: current
      });

      if (this.data.type !== 'history') {
        wx.getStorage({
          key: 'historyPreview',
          success: res => {
            let arr = JSON.parse(res.data);
            if (arr.some(v => v.cardId == this.data.cardInfo.cardId || v.relCardId == this.data.cardInfo.cardId)) arr.splice(arr.findIndex(v => v.cardId == this.data.cardInfo.cardId || v.relCardId == this.data.cardInfo.cardId), 1);
            arr.unshift(this.data.cardInfo);
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'historyPreview'
            });
          },
          fail: res => {
            let arr = [this.data.cardInfo];
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'historyPreview'
            });
          }
        });
      };
    };
  },
  imageChange(e) {
    let {
      current
    } = e.detail;
    let {
      index
    } = e.currentTarget.dataset;
    let str = `memberList[${index}].current`;
    this.setData({
      [str]: current
    });
  },

  // 拨号
  callCard() {
    if (this.data.joinCardId == 'null') {
      wx.showToast({
        title: '您不是该组成员，无法拨打电话',
        icon: 'none'
      });
      return
    };
    wx.makePhoneCall({
      phoneNumber: this.data.cardInfo.phone,
      success: res => {
        let data = {
          avatar: this.data.cardInfo.avatar,
          name: this.data.cardInfo.userName,
          phone: this.data.cardInfo.phone,
          firstPy: this.data.cardInfo.firstPy,
          date: new Date().getTime()
        };
        wx.getStorage({
          key: 'callLog',
          success: res => {
            let arr = JSON.parse(res.data);
            if (arr.some(v => v.phone == data.phone)) arr.splice(arr.findIndex(v => v.phone == data.phone), 1);
            arr.unshift(data);
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'callLog'
            });
          },
          fail: res => {
            let arr = [data];
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'callLog'
            });
          }
        });
      }
    });
  },
  // 复制剪切板
  setClipboard() {
    if (this.data.joinCardId == 'null') {
      wx.showToast({
        title: '您不是该组成员，无法复制手机号',
        icon: 'none'
      });
      return
    };
    wx.setClipboardData({
      data: this.data.cardInfo.phone,
      success: res => {
        wx.showToast({
          title: '已复制手机号',
          icon: 'success'
        });
      }
    });
  },
  bindgetuserinfo(e) {
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo;
      this.addCard();
    };
  },
  // 添加
  addCard() {
    if (this.data.joinCardId == 'null') {
      wx.showToast({
        title: '您不是该组成员，无法保存名片',
        icon: 'none'
      });
      return
    };
    if (this.data.cardInfo.ableAdd) {
      if (this.data.isRequest) {
        return
      };
      this.setData({
        isRequest: true
      });

      toMailList(this.data.cardInfo.cardId).then(res => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            mask: true,
            duration: 1500
          });
          this.setData({
            isRequest: false,
            'cardInfo.ableAdd': false,
            [`memberList[${this.data.wallCurrent}].ableAdd`]: false
          });
        };
      });
    } else {
      if (this.data.cardInfo.owner) {
        wx.showToast({
          title: '这是自己的名片...',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '您已经保存过了...',
          icon: 'none'
        });
      };
    };
  },

  // 查看名片详细信息
  previewCardInfo(e) {
    let {
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/cardDetails/index?from=swiper&cardId=${id}&joinCardId=${this.data.joinCardId}`
    });
  },

  goback() {
    wx.navigateBack({
      delta: 1
    });
  }
})